package com.chuxing.system.service.impl;

import com.chuxing.config.ExamState;
import com.chuxing.domain.Exam;
import com.chuxing.system.mapper.ExamMapper;
import com.chuxing.system.service.AsyncService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author LiuQi
 * @create 2025-01-01-12:39
 */
@Service
@RequiredArgsConstructor
@Slf4j
@Transactional
public class AsyncServiceImpl implements AsyncService {
    private final ExamMapper examMapper;

    @Override
    @Async
    public void uploadAsync(List<Exam> examList){
        // 遍历Exam列表，更新或插入考试信息
        // 定义一个容器保存需要插入的数据
        List<Exam> insertExamList=new ArrayList<>();
        for (Exam value : examList) {
            log.info("正在解析excel文件:学号:{}、成绩:{}", value.getStudentId(), value.getExamScore());
            Exam exam = examMapper.selectExamByStudentId(value.getStudentId());
            // 判断考试信息是否已存在，如果已存在且考试分数不一致，则更新考试信息
            if (exam != null) {
                if(exam.getExamScore()==null ||!exam.getExamScore().equals(value.getExamScore())){
                    // 更新现有考试信息
                    exam.setExamScore(value.getExamScore());
                    examMapper.updateExam(exam);
                }
            } else {
                // 插入新的考试信息
                Exam addExam = new Exam();
                addExam.setStudentId(value.getStudentId());
                addExam.setExamScore(value.getExamScore());
                addExam.setExamState(ExamState.EXAM);
                // 设置考试日期和时间
                addExam.setExamDate(LocalDate.now());
                addExam.setExamTime(LocalTime.now());
                // 设置创建时间和更新时间
                addExam.setCreateTime(LocalDateTime.now());
                addExam.setUpdateTime(LocalDateTime.now());
                // 添加到插入数据容器中
                insertExamList.add(addExam);
            }
        }
        if(!insertExamList.isEmpty()){
            examMapper.insert(insertExamList);
        }
        log.info("解析excel文件完成");
    }
}
